﻿using System;
using RepositoryAndEf.Core.Data;
using RepositoryAndEf.Domain;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Moq;

namespace RepositoryAndEf.Service.Tests
{
    public class ShoppingCartServiceTests
    {

        private IList<ShoppingCart> GetMockShoppingCartObjects()
        {
            return new List<ShoppingCart>() { 
                new ShoppingCart{ Id= Guid.NewGuid()},
                new ShoppingCart{ Id= Guid.NewGuid()},
                new ShoppingCart{ Id= Guid.NewGuid()},
            };
        }

        private IList<Product> GetMockProductObjects()
        {
            return new List<Product>()
            {
                new Product{ Id=Guid.NewGuid()},
                new Product{ Id=Guid.NewGuid()},
                new Product{ Id=Guid.NewGuid()},
            };
        }

        public void AddToCart_WithExpectedParameters_Success()
        {
            var products = GetMockProductObjects();
            var shoppingCarts = GetMockShoppingCartObjects();

            var shoppingCartRepositoryMoq = new Mock<IRepository<ShoppingCart>>();
            var productRepositoryMoq = new Mock<IRepository<Product>>();

            shoppingCartRepositoryMoq.Setup(r => r.Insert(It.IsAny<ShoppingCart>())).Callback<ShoppingCart>(
                cart => shoppingCarts.Add(cart));

            shoppingCartRepositoryMoq.Setup(r => r.GetById(It.IsAny<Guid>())).Returns(
                (Guid id) =>
                {
                    return shoppingCarts.FirstOrDefault(c => c.Id == id);
                });

            shoppingCartRepositoryMoq.Setup(r => r.Update(It.IsAny<ShoppingCart>())).Returns((ShoppingCart cart) =>
            {
                var existingCart = shoppingCarts.FirstOrDefault(c => c.Id == cart.Id);
                if (existingCart == null)
                {
                    throw new InvalidOperationException("Attampt to update unexiting shopping cart.");
                }
                existingCart = cart;
                return true;
            });

            productRepositoryMoq.Setup(p => p.Insert(It.IsAny<Product>())).Callback<Product>(
                p => products.Add(p));

            productRepositoryMoq.Setup(p => p.GetById(It.IsAny<Guid>())).Returns((Guid id) =>
            {
                return products.FirstOrDefault(p => p.Id == id);
            });


            var shoppingCartService = new ShoppingCartService(shoppingCartRepositoryMoq.Object, productRepositoryMoq.Object);

            var cartId = shoppingCarts[0].Id;
            var productId = products[0].Id;

            var retCart = shoppingCartService.AddToCart(cartId, productId, 20);

        }
    }
}
